/**
 * @name AvatarSelector
 * @author darcrand
 * @desc
 */

import React, { Component } from 'react'
import Scrollbar from 'smooth-scrollbar'

import { Button } from '@/components'
import styles from './styles.module.less'
import avatars from '@/assets/images/avatars.json'

const fixedElements = Array(10).fill(0)

class AvatarSelector extends Component {
  static defaultProps = {
    visible: false,
    onCancel: () => {},
    onConfirm: src => {}
  }

  state = {
    src: ''
  }

  refScroll = React.createRef()
  scrollIns = null

  componentDidMount() {
    this.scrollIns = Scrollbar.init(this.refScroll.current)
  }

  componentWillUnmount() {
    this.scrollIns && this.scrollIns.destroy()
  }

  onSelect = src => {
    this.setState({ src })
  }

  onConfirmAvatar = () => {
    this.props.onConfirm(this.state.src)
  }

  render() {
    const { visible, onCancel } = this.props
    const { src } = this.state

    return (
      <div className={visible ? styles.container : `${styles.container} ${styles.hide}`}>
        <div className={styles['content-wrapper']}>
          <div ref={this.refScroll} className={styles['list-wrapper']}>
            <ul className={styles['list']}>
              {avatars.map(v => (
                <li
                  key={v}
                  className={v === src ? `${styles.item} ${styles.active}` : styles.item}
                  style={{ backgroundImage: `url("${v}")` }}
                  title={v}
                  onClick={() => this.onSelect(v)}
                ></li>
              ))}

              {fixedElements.map((v, i) => (
                <li key={i} className={styles['item-fixed']} />
              ))}
            </ul>
          </div>

          <div className={styles['button-bar']}>
            <Button onClick={onCancel}>cancel</Button>
            <Button disable={!src} onClick={this.onConfirmAvatar}>
              confirm
            </Button>
          </div>
        </div>
      </div>
    )
  }
}

export default AvatarSelector
